load("js/luajs/ccb_luaFunc.js")
var cardNum = 0;
//是否存在卡信息，初始化false 为存在卡信息
var existCard = false;
//是否存在信用卡信息，初始化为true，默认有信用卡信息
var existCredit = true;
//是否存在借记卡信息，初始化为true，默认有借记卡信息
var existDebit = true;
var loginUrl = "https://ibsbjstar.ccb.com.cn/CCBIS/V6/STY1/CN/login.jsp";
var isNeedSms = false;

var v4_ccb_java_funcs = {
    openHomePage : function(){
        //建设银行官网首页
        var loginText = get(loginUrl);
        context.put("loginText", loginText);
        saveHtmlAndImage("homePage")
        saveIframeHtmlAndImage("{'fQRLGIN'}", "homePageFrame")
    },
    checkProxyAvailable: function () {
        var html = context.get("loginText");
        //根据返回页面信息判断是不是代理ip异常
        if (html.contains("代理服务器没有响应") || html.contains("无法显示此页") || html.contains("Hypertext Transfer Protocol")) {
            logger.info("CCB taskKey = " + context.get(Constants.LUA_TASK_KEY) + " 代理IP异常");
            return false;
        } else {
            //如果代理没有问题，保存当前页面并返回true，进入下一步
            return true;
        }
    },
    checkTargetWebsiteAvailable:function () {
        return checkFrameStatus();
    },
    checkControlAvailable:function () {
        return true;
    },
    needResetEnvironment:function(){
        //getProxyInfo(context);
        context.put("proxyAvailable",false);
        return equals(context.get("currentErrorCode"), BALO_99601_10) || equals(context.get("currentErrorCode"),BALO_99601_30);
    },

//-DproxyStr=106.75.34.191:808
    login:function () {
        var index_html_frame = get_frame_html("fQRLGIN");
        storeDataToFile(context, index_html_frame, "index_html_frame.html");
        var loginedHtml;
        login(getLoginParams(context)[0], context.get(Constants.LUA_TASK_TOKEN));
        Thread.sleep(10000);
        loginedHtml=  saveHtmlAndImage("loginResult");
        //获取frame的名称
        var frameFlag = getFrameFlag(loginedHtml);
        var smsHtml = get_frame_html(frameFlag);

        //增加页面是否渲染完成的判断
        for(var i = 0; i < 10; i++){
            if ((StringUtils.isNotBlank(getLoginErrorMsg(loginedHtml,smsHtml)) && !(getLoginErrorMsg(loginedHtml,smsHtml)).contains("登录超时")) || loginedHtml.contains("中国建设银行网上银行个人登录验证") || loginedHtml.contains("私密问题")  || equals(Jsoup.parse(loginedHtml).select("title").text(), "中国建设银行个人网上银行")){
                logger.info("任务【{}】,页面渲染完成",context.get(LUA_TASK_KEY));
                break;
            } else if (smsHtml.contains("为让您更安全地使用网上银行，现对您当前使用的设备进行安全认证")){
                logger.info("任务【{}】，需要进行短信认证",context.get(LUA_TASK_KEY));
                isNeedSms = true;
                break;
            } else if (i > 3 && loginedHtml.contains("请尽量使用专用电脑操作网上银行，并定期更新操作系统安全补丁和杀毒软件")){
                //如果重试三次之后仍停留在首页，需要再次点击确定按钮
                logger.info("任务【{}】，第一次未点击上登录按钮，单独调用点击事件",context.get(LUA_TASK_KEY));
                click_login_button2();
            }  else {
                logger.info("任务【{}】,页面渲染未完成，继续循环等待",context.get(LUA_TASK_KEY));
                Thread.sleep(5000)
                loginedHtml=  saveHtmlAndImage("loginResult");
                smsHtml = get_frame_html(frameFlag);
            }
        }
        storeDataToFile(context, smsHtml, "smsHtml.html");

        //var loginedHtml = FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\2018_08_05_11_44_21_loginResult.html"));
        //中国建设银行网上银行个人登录验证
        if(loginedHtml.contains("中国建设银行网上银行个人登录验证") && loginedHtml.contains("私密问题")){
            var questions = new ArrayList();
            questions.add("你的出生地");
            context.put(TASK_QUESTIONS, questions);
            var answer = waitAnswerBySeconds(context,300);

            logger.info("任务taskKey = {} 答案 {},答案的类型是{}", context.get(LUA_TASK_KEY), answer,typeof(answer));
            logger.info("任务taskKey = {}, 显示窗口", context.get(LUA_TASK_KEY));
            var result = JSON.parse(setAnster(answer));
            if(Boolean.valueOf(result.getString("simiwemti")) && Boolean.valueOf(result.getString("fangweiwenti"))){
                clickButon();
            }
            Thread.sleep(2000);
            loginedHtml = saveHtmlAndImage("answerloginResult");
        }

        if(isNeedSms){
            //需要短信认证
            logger.info("建设银行 taskKey:{} 开始等待短信验证码时间{}",context.get(LUA_TASK_KEY));
            var smsCode = waitSmsCodeBySeconds(context, 120);
            logger.info("建设银行 taskKey:{} 等待短信结果{}",context.get(LUA_TASK_KEY),smsCode);
            //action开始: 校验短信验证码
            var isSmsCodeCorrectFunc = function(smsCode) {
                return StringUtils.isNotBlank(smsCode);
            }
            var getSmsCodeErrorMsgFunc = function(smsCode) {
                return "短信验证码超时"
            }
            assertTrueOrThrowException(smsCode, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc)
            //输入短信验证码
            set_frame_input_text_by_id("TRANSMSCODE",smsCode,frameFlag);
            //判断输入短信结果
            var inputMsg = getSmsInputResult(frameFlag);
            logger.info("任务【{}】,短信验证码输入结果为【{}】",context.get(LUA_TASK_KEY),inputMsg);
            var isRightInputSmsCodeCorrectFunc = function(inputMsg) {
                return StringUtils.isNotBlank(String.valueOf(inputMsg));
            }
            var getErrorInputSmsCodeErrorMsgFunc = function() {
                return "短信验证码错误"
            }
            assertTrueOrThrowException(inputMsg, isRightInputSmsCodeCorrectFunc, getErrorInputSmsCodeErrorMsgFunc)
            //点击确定按钮
            clickSmsButton(frameFlag);
            //判断页面是否渲染完成
            loginedHtml = saveHtmlAndImage("smsInputResult");
            frameFlag = getFrameFlag(loginedHtml);
            var smsInputResult = get_frame_html(frameFlag);
            var isLogin = false;
            for(var i=0 ;i<10;i++){
                if(equals(Jsoup.parse(loginedHtml).select("title").text(), "中国建设银行个人网上银行")){
                    //登录成功或者短信错误，跳出
                    logger.info("任务【{}】,短信校验成功，登陆成功",context.get(LUA_TASK_KEY));
                    isLogin = true;
                    break;
                } else if (!smsInputResult.contains("return is null") && StringUtils.isNotBlank(smsInputResult) && !smsInputResult.contains("为让您更安全地使用网上银行，现对您当前使用的设备进行安全认证")){
                    logger.info("任务【{}】,短信校验失败，登陆失败",context.get(LUA_TASK_KEY));
                    isLogin = false;
                    break;
                } else{
                    logger.info("任务【{}】，短信输入之后页面渲染未完成，继续等待",context.get(LUA_TASK_KEY));
                    Thread.sleep(5000)
                    clickThePage();
                    smsInputResult = get_frame_html(frameFlag);
                    loginedHtml = saveHtmlAndImage("smsInputResult");
                }
            }
            storeDataToFile(context, smsInputResult, "smsInputResult.html");

            //判断是否登录成功
            var isRightLoginCorrectFunc = function() {
                return isLogin;
            }
            var getLoginErrorMsgFunc = function(smsInputResult) {
                if(smsInputResult.contains("您输入的短信动态口令不正确，请重新输入") || smsInputResult.contains("短信动态口令输入错误次数已达三次")){
                    return "短信验证码错误"
                }else if(smsInputResult.contains("您的操作已超时（短信动态口令3分钟内有效），请重新获取")){
                    return "短信验证码超时"
                } else {
                    return "短信验证码错误"
                }

            }
            assertTrueOrThrowException(smsInputResult, isRightLoginCorrectFunc, getLoginErrorMsgFunc)

        } else {
            var isLoginCorrectFunc = function (loginedHtml) {
                return !equals(loginedHtml,"") &&  equals(Jsoup.parse(loginedHtml).select("title").text(), "中国建设银行个人网上银行");
            }
            var getLoginErrorMsgFunc = function(loginedHtml){
                return getLoginErrorMsg(loginedHtml,smsHtml);
            }
            assertTrueOrThrowException(loginedHtml, isLoginCorrectFunc, getLoginErrorMsgFunc);
        }
        logger.info("任务【 {} 】,登录成功。", context.get(LUA_TASK_KEY));
        //进入主页后获取抓取必要参数
        judgeRightMainHtml();
    },
    crawl: function () {
        var beforeCrawl =  saveHtmlAndImage("beforeCrawlPage");
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始抓取信息");
        //从ThreadLocal中获取用户信息和url信息
        var userInfo = context.get("jsonUserInfo");
        var urlInfo = context.get("jsonUrlInfo");
        //获取每个人访问所需的URL 每个人的URL不同
        var individualUrl = urlInfo.getString("P1ACTION");
        //若火没有获取到用户的Url则抛异常
        if (individualUrl.equals("") || individualUrl == null) {
            logger.error("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 基础请求信息获取失败,停止抓取");
            throw new BankException(BankConstants.BACR_20306_30, " 基本请求信息获取失败,停止抓取");
        }
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取信用卡卡号列表");
        //创建存放信用卡信息和借记卡信息的list
        var creditList = new ArrayList();
        var debitList = new ArrayList();
        //拼接获取卡信息参数的url
        var cardHomeUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&USERID=%s&BRANCHID=%s&SKEY=%s&TXCODE=310103";
        cardHomeUrl = String.format(cardHomeUrl, userInfo.getString("USERID"), userInfo.getString("BRANCHID"), userInfo.getString("SKEY"));
        //发送请求并保存页面
        var html = ajax_get(cardHomeUrl);
        storeDataToFile(context, html, "cardCategory.html")
        //获取页面hidden的一些参数 接下来的请求需要
        var doc = Jsoup.parse(html);
        var elements = doc.select("#jhform > input");
        var map = new LinkedHashMap();
        //解析jhform中的所有input中参数信息
        if (elements !== null && elements.size() > 0) {
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 填充accountInfo账户信息的请求参数获取");
            for (var i = 0; i < elements.size(); i++) {
                var key = elements.get(i).attr("name");
                var value = elements.get(i).attr("value");
                map.put(key, value);
            }
        } else {
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " accountInfo账户信息的请求参数获取，失败为空，继续抓取");
        }
        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始请求获取用户储蓄卡列表");
        //储蓄卡列表URL拼接
        var cardListUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&TXCODE=310102&USERID=%s&BRANCHID=%s&SKEY=%s&SELECT_TYPE=cxzh";
        cardListUrl = String.format(cardListUrl, userInfo.getString("USERID"), userInfo.getString("BRANCHID"), userInfo.getString("SKEY"));
        //用获取到的页面发送ajax请求
        var depositCardList = ajax_get(cardListUrl);
        //保存到借记卡列表页面中
        storeDataToFile(context, depositCardList, "depositCardList.html")
        var creditCardList = new ArrayList();
        try {
            //获取所有的借记卡的卡片信息若出现异常catch住，继续抓取信用卡信息
            creditCardList = getAllDePositCardInfo(depositCardList);
        } catch (e) {
            statCaughtException(context, e);
            logger.error("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + "获取用户账户列表(借记卡列表)信息失败", e);
        }
        //如果获取到借记卡信息为0则不做借记卡解析，继续抓取信用卡
        if (creditCardList.size() == 0) {
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 用户借记卡片信息获取为0张,结束抓取");
            existDebit = false;
        } else {
            //拼接获取跳转到查询借记卡明细的页面的url
            var srcUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&PT_LANGUAGE=CN&PT_STYLE=1&TXCODE=N31010&SKEY=%s&USERID=%s&BRANCHID=%s&SKEY=%s";
            srcUrl = String.format(srcUrl, userInfo.getString("SKEY"), userInfo.getString("USERID"), userInfo.getString("BRANCHID"), userInfo.getString("SKEY"));
            //参数从这个frameHtml中获取
            var frameHtml = ajax_get(srcUrl);
            var framedoc = Jsoup.parse(frameHtml);
            //Jsoup解析页面上为明细字样的span
            var el = framedoc.select("#scrollPic > ul > li > div > div > div.pbd_cxdiv > span[data_id=mingxi]");
            //遍历获取所有卡参数值并拼接成url存在lua的table中
            for (var i = 0; i < el.size(); i++) {
                var val = el.get(i).attr("values");
                //获取到必要参数,并拼接跳转url
                getSrcUrl2(Integer.parseInt(i), val);
            }

            //遍历下载每张借记卡的账单明细TXT并进行解析
            for each (var creditCardAllData in creditCardList){
                cardNum++;
                var billHtml = "";
                //下载明细EXCEL/TXT,返回本地储存路径
                try {
                    var imagePath = getScreenShots();
                    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 跳转到第" + cardNum + "张储蓄卡账单明细下载页之前页面的截图路径" + imagePath);
                    storeDataToFile(context, imagePath, "BeforeGoToDownloadHtmlPath.txt")
                    //进入第N张卡的账单流水信息下载页
                    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 跳转到第" + cardNum + "张储蓄卡账单明细下载页");
                    //下载TXT文件的消费明细，cardNum为第几张卡，此索引和lua中存跳转url的table索引值相同
                    billHtml = downloadBill(cardNum, creditCardAllData);
                } catch (e){
                    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 下载第" + cardNum + "张借记卡的EXCEL/TXT失败!!!");
                    statCaughtException(context, e);
                }
                //解析TXT 如果不包含“无账单明细”则有明细信息，继续解析
                if (!billHtml.equals("无账单明细")) {
                    try {
                        //解析txt方法
                        parseBillForTxt(billHtml, creditCardAllData);
                        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张借记卡的TXT成功!");
                    } catch (e) {
                        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张借记卡的TXT失败!!!");
                        statCaughtException(context, e);
                        // throw new BankException(BankConstants.BACR_20306_30, "解析账单明细TXT出错!!!" + e);
                    }
                }
                try {
                    //获取每张卡的deposits账户信息
                    crawlDeposit(creditCardAllData, map);
                    //通过明细计算余额的公共方法
                    DebitBalanceUtil.sumBalance(creditCardAllData);
                    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取第" + cardNum + "张借记卡的储蓄信息成功!");
                } catch (e) {
                    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取第" + cardNum + "张借记卡的储蓄信息失败!!!");
                    statCaughtException(context, e);
                }
                logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 完成第" + cardNum + "张借记卡的信息采集!");
                Thread.sleep(1000);
            }
        }

        //获取cardList.html中信用卡卡信息
        if(context.get("creditCardListHtml")!=null){
            //取出上下文中保存的信用卡的list信息
            var creditCardAllDataList = getAllCardInfo(context.get("creditCardListHtml"));
            //如果获取的list长度为0，则视为无信用卡信息
            if (creditCardAllDataList.size() == 0) {
                logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 信用卡号信息获取失败，停止抓取取");
            }else{
                logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取到的卡为" + creditCardAllDataList.size() + "张");
                cardNum++;
                //信用卡多张卡要合并处理，所以这里可以直接get(0),不做循环
                var cardAllData = creditCardAllDataList.get(0);
                try {
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " crawlLimit抓取卡额度等基本信息");
                    crawlLimit(cardAllData);
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " crawlUndoneBill抓取卡未出账单信息");
                    crawlDoneBill(cardAllData);
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " computeUnbillDate计算卡未出账单的lastBalance");
                    crawlUndoneBill(cardAllData);
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " crawlDoneBill抓取卡已出账单信息");
                    computeUnBillLastBalance(cardAllData);
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " computeUnbillDate计算卡未出账单的lastBalance结束");
                }catch(e){
                    logger.error("CCBBank:taskKey={}",context.get(Constants.LUA_TASK_KEY), e);
                    statCaughtException(context, e);
                }
                var fullCardNo = new StringBuilder();
                var fourCardNo = new StringBuilder();

                for each (var creditCardAllData in creditCardAllDataList) {
                    if ("".equals(fullCardNo.toString())) {
                        fullCardNo.append(creditCardAllData.getFullCardNum());
                        fourCardNo.append(creditCardAllData.getFullCardNum().substring(creditCardAllData.getFullCardNum().length() - 4, creditCardAllData.getFullCardNum().length()));
                    } else {
                        fullCardNo.append("," + creditCardAllData.getFullCardNum());
                        fourCardNo.append("," + creditCardAllData.getFullCardNum().substring(creditCardAllData.getFullCardNum().length() - 4, creditCardAllData.getFullCardNum().length()));
                    }

                }
                cardAllData.setFullCardNum(fullCardNo.toString());
                cardAllData.setCardNum(fourCardNo.toString());
                creditList.add(cardAllData);
            }
        }
        if(!existDebit&&!existCredit){
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 抓取过程中出现异常");
            throw new BankException(BankConstants.BALO_20304_30, "未获取到卡片信息")
        }

        debitList.addAll(creditCardList);
        context.put(Constants.CREDIT_DATA, creditList);
        context.put(Constants.DEBIT_DATA, debitList);
    },
    exitLogin :function () {
    },
    exit:function () {
    }
}

function getErrorMsg(){
    return "请核对用户名";
}

/**
 * 判断是否进入主页
 */
function judgeRightMainHtml(){
    logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + "获取基本的请求数据信息");
    //获取当前页面的html
    var html = get_html();
    storeDataToFile(context, html, "mainHtml_.html")
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 成功跳转到主页");
    //通过正则表达式获取到userInfo信息，userInfo信息格式为
    /**
     * {<br>
     * "USERID": "23108319******1811",<br>
     * "BRANCHID": "11000****",<br>
     * "SKEY": "urYGuh",<br>
     * "NAME":"徐**",<br>
     * "NICKNAME":"徐**",<br>
     * "SEX":"M",<br>
     * "TEL":",1581122****",<br>
     * "IP":"111.200.243.194",<br>
     * "SAFECTRL_TYPE":"J,U,",<br>
     * "IS_PBC":"0",<br>
     * "ECIF_CUSTNO":"72019000010376****",<br>
     * "SIGNSTATUS":"C",<br>
     * "GMUKEY":"",<br>
     * "LOGIN_NUM":"144",<br>
     * "CAN_TXTU":"0",<br>
     * "CAN_USECR":"1",<br>
     * "YXSJ_Flag":"",<br>
     * "PRI_STATIC_TWCODE":"",<br>
     * "CRDNO_CHANGEPURSE":"",<br>
     * "CAN_USEGRZC":"0",<br>
     * "CAN_CANUSEQRCHK":"0",<br>
     * "CAN_USECUSTMAN":"0"<br>
     * }<br>
     */
    var userInfo = RegexUtils.GetText(html, "var DAT_USERBASE=_DAT_USERBASE = (\\{[\\s\\S]*?\\})").replace("\\", "");
    //如果userInfo信息为空，则获取基础信息失败，停止抓取
    if (userInfo.equals("") || userInfo == null) {
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + "基础请求信息获取失败，停止抓取");
        throw new BankException(BankConstants.BALO_23001_10, "基本请求信息获取失败，停止抓取");
    }
    //获取登录url信息，url信息格式如下
    /**
     * "P1ACTION": "/CCBIS/B2CMainPlat_06?SERVLET_NAME=B2CMainPlat_06&CCB_IBSVersion=V6&PT_STYLE=1",
     * "WEB_PATH": "/P1StaRes/V6/STY1/CN/",
     * "strServletName": "B2CMainPlat_06",
     * "PT_STYLE": "",
     * "PT_LANGUAGE": "",
     * "SHOW_RELTXS":"1",
     * "SEC_TIMEOUT": 600,
     * "ON_SRAUTOLOGIN":"1",
     * "AVI_SWITCH2EBS": 0,
     * "IS_SHOWNICHKNAME": 1,
     * "QRQM_LOGINNUM_LMT":"1",
     * "TXFLW04AD_MUSTSHOW":"1",
     * "ON_DATCOL_DOONALLAP": 0,
     * "IS_SHOWCUSTSTARLEV":"1",
     * "IS_SHOWDF":"1",
     * "ON_BLKQ":"1",
     * "ON_NEWPBC_BANK":"0",
     * "IS_SHOWMB":"1"
     */
    var urlInfo = RegexUtils.GetText(html, "var DAT_ENVBASE=_DAT_ENVBASE = (\\{[\\s\\S]*?\\})").replace("\\", "");
    //如果urlInfo信息为空，则获取基础信息失败，停止抓取
    if (urlInfo.equals("") || urlInfo == null) {
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + "基础请求信息获取失败，停止抓取");
        throw new BankException(BankConstants.BALO_23001_10, "基本请求信息获取失败，停止抓取");
    }
    //把userInfo和urlInfo转为Json对象，并存放到ThreadLocal中，作为全局变量
    var jsonUserInfo = JSON.parseObject(userInfo);
    var jsonUrlInfo = JSON.parseObject(urlInfo);
    context.put("jsonUserInfo",jsonUserInfo);
    context.put("jsonUrlInfo",jsonUrlInfo);
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 完成基本请求信息成功");
    //完成基本请求信息后保存截图
    var path = getScreenShots();
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 登录成功后进入主页截图路径 " + path);
    storeDataToFile(context, path, "LoginedHtmlPath.txt")

    //获取每个人访问所需的URL 每个人的URL不同
    var individualUrl = jsonUrlInfo.getString("P1ACTION");
    if (individualUrl.equals("") || individualUrl == null) {
        logger.error("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 基础请求信息获取失败,停止抓取");
        throw new BankException(BankConstants.BALO_23001_10, " 基本请求信息获取失败,停止抓取");
    }
    var imagePath = getScreenShots();
    logger.info("CCB taskKey = " + context.get(Constants.LUA_TASK_KEY) + " 查看有几张信用卡截图路径" + imagePath);
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取信用卡卡号列表");
    //拼接查询信用卡列表url
    var balanceUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&USERID=%s&BRANCHID=%s&SKEY=%s&TXCODE=XE1110&TYPE_FLAG=1";
    balanceUrl = String.format(balanceUrl, jsonUserInfo.getString("USERID"), jsonUserInfo.getString("BRANCHID"), jsonUserInfo.getString("SKEY"));
    //获取信用卡列表页面
    var cardListHtml = ajax_get(balanceUrl);
    //保存页面到cardList.html
    storeDataToFile(context, cardListHtml, "cardList.html")
    //放到上下文中，抓取是用到此页面
    context.put("creditCardListHtml", cardListHtml);
    var imagePath1 = getScreenShots();
    logger.info("CCB taskKey = " + context.get(Constants.LUA_TASK_KEY) + " 查看卡列表截图路径" + imagePath1);
    storeDataToFile(context, imagePath1, "cardHtmlPath.txt")
    //判断页面上如果有持卡人信息记录不存在或者所对应的异常代码"YDCA02813000"或信用卡"信用卡查询"，则判定为没有信用卡信息
    if (cardListHtml.contains("持卡人信息记录不存在。") || cardListHtml.contains("YDCA02813000")||!cardListHtml.contains("信用卡查询")) {
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 持卡人没有信用卡信息");
        //该字段置为false;
        existCredit = false;
    } else{
        //获取cardList.html中信用卡卡信息，可能为多张卡，所以是list
        var creditCardAllDataList = getAllCardInfo(cardListHtml);
        //如果返回的list.size()为0,则判定为没有卡号信息
        if (creditCardAllDataList.size() == 0) {
            logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 卡号信息获取失败，停止抓取取");
            existCredit = false;
        }else{
            logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 获取到的卡为" + creditCardAllDataList.size() + "张");
        }
    }
    return;
}


/**
 * 获取信用卡多张卡
 *
 * @param cardListHtml
 */
function getAllCardInfo(cardListHtml) {
    var creditCardAllDataList = new ArrayList();
    //使用Jsoup解析html
    var doc = Jsoup.parse(cardListHtml);
    //通过css选择器获取到卡列表所在trs
    var trs = doc.select("#result_1 > tbody:nth-child(1) >tr");
    //每张卡有3行 一行是卡号 一行是人民币额度 一行是美元额度，第一行是标题，所以index从1开始
    for (var index = 1; index < trs.size(); index ++) {
        //创建一个银行类
        var creditCardAllData = getCreditCardAllData();
        //获取每个tr中的td
        var tds = trs.get(index).select("td");
        var cardNo = "";
        var cardBank = "";
        //如果获取卡号和开户行所在td不为null则继续解析
        if (tds.select("[name='strAcc_No']") !== null && tds.select("[name='strAcc_No']")!="" && tds.select("[name='branch_code']") !== null) {
            //获取卡号
            cardNo = tds.select("[name='strAcc_No']").val();
            //获取开户行
            cardBank = tds.select("[name='branch_code']").val();
            //获取卡号做非空判断
            if (!StringUtils.isBlank(cardNo)) {
                //抓取到卡号并赋值
                creditCardAllData.setFullCardNum(cardNo);
                //获取卡号的末4位
                creditCardAllData.setCardNum(cardNo.substring(cardNo.length() - 4, cardNo.length()));
                creditCardAllData.setOpenBank(cardBank);
                creditCardAllDataList.add(creditCardAllData);
            }
            logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + "获取第" + index + "张信用卡信息");
        }
    }
    return creditCardAllDataList;
}



/**
 * @param cardListHtml
 */
function getAllDePositCardInfo(cardListHtml) {
    var creditCardAllDataList = new ArrayList();
    var doc = Jsoup.parse(cardListHtml);
    //Jsoup解析Html，通过css选择器获取卡信息所在tr的集合
    var trs = doc.select("tr:not(.trbg):not(.tab_qymey_td):not(:first-child):not([hasblance='0'])");
    var  urlInfo;
    try {
        urlInfo = context.get("jsonUrlInfo");
        for (var index = 0; index < trs.size(); index++) {
            //创建一个银行卡信息类
            var creditCardAllData = getCreditCardAllData();
            //获取每张卡对应tr中的td
            var tds = trs.get(index).select("td");
            //tds>=10是为了过滤隐藏的tr，其中只有一个td
            if (tds.size() >= 10) {
                //拼接获取卡信息的url
                var url = "https://ibsbjstar.ccb.com.cn" + urlInfo.getString("P1ACTION") + "&TXCODE=N31001&SKEY=%s&USERID=%s&BRANCHID=%s&ACC_NO=%s&ACC_TYPE_FLAG=lct&CurTypeDesc=人民币&AccAlias=%s&AgreeType=C&BranchDesc=&SEND_USERID=&NOACCTJ=1";
                //从a标签的onclick时间中取到包含卡号的参数
                var cardNo = tds.get(6).select("a").get(0).attr("onclick");
                //对卡号参数进行格式化处理，参数中已“,”分割，第一个是卡号
                var formatCardNo = formatNumber(cardNo.split(",")[0]);
                //从第八个td中取到开户行
                var openBank = tds.get(7).text();
                var jsonUserInfo = context.get("jsonUserInfo");
                //格式化url，给url中的参数赋值
                url = String.format(url, jsonUserInfo.get("SKEY"), jsonUserInfo.get("USERID"), jsonUserInfo.get("BRANCHID"), formatCardNo, openBank);
                //发送请求
                var html = ajax_get(url);
                //请求后获取开户时间
                var doc1 = Jsoup.parse(html);
                var trs1 = doc1.select("tr");
                //开户时间初始化为""
                var openTime = "";
                //借记卡中可能有多个账户，比如整存整取，活期
                if (trs1.size() > 3) {
                    //循环所有的账户，取到每一个账户的开户时间，取最早的一个作为开卡时间
                    for (var i = 3; i < trs1.size(); i++) {
                        var openTime1 = trs1.get(i).select("td").get(0).text();
                        if (!"".equals(openTime) && openTime.compareTo(openTime1) > 0) {
                            openTime = openTime1;
                        } else if ("".equals(openTime)) {
                            openTime = openTime1;
                        }
                    }
                }
                //做非空判断，不是空字符串则格式化并赋值
                if(!"".equals(openTime)) {
                    creditCardAllData.setOpenTime(formatDate(openTime));
                }
                //如果获取到的卡号不为空则格式化并赋值
                if (!StringUtils.isBlank(formatCardNo)) {
                    creditCardAllData.setFullCardNum(formatCardNo);
                    creditCardAllData.setCardNum(formatCardNo.substring(formatCardNo.length() - 4, formatCardNo.length()));
                }
                //如果开户行不为空，则赋值
                if (!StringUtils.isBlank(openBank)) {
                    creditCardAllData.setOpenBank(openBank);
                }
                //已\n为分隔符号，获得一个billLines数组
                var basicInfo = context.get("jsonUserInfo");
                creditCardAllData.setBankName("建设银行");
                creditCardAllData.setCardId(UUID.randomUUID().toString());
                creditCardAllData.setCardType("借记卡");
                creditCardAllData.setNameOnCard(basicInfo.getString("NAME"));
                //最后将抓取到的卡信息放到全局卡集合中并返回
                creditCardAllDataList.add(creditCardAllData);
            }
        }
    }catch(e){
        logger.error("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + "获取用户账户列表(借记卡列表)信息失败", e);
        statCaughtException(context, e);
    }
    return creditCardAllDataList;
}

function computeUnBillLastBalance(cardAllData) {
    var last_balance = BigDecimal.ZERO;
    if(cardAllData.getBills()!==null&&cardAllData.getBills().size()>1&&cardAllData.getBills().get(1)!==null){
        last_balance = cardAllData.getBills().get(0).getNewBalance();
        cardAllData.getBills().get(cardAllData.getBills().size()-1).setLastBalance(last_balance);
        var expenses = cardAllData.getBills().get(cardAllData.getBills().size()-1).getShoppingSheets();
        for each (var expense in expenses) {
            last_balance = last_balance.add(expense.getAmountMoney());
        }
    }
    cardAllData.getBills().get(cardAllData.getBills().size()-1).setNewBalance(CreditResultUtil.StringToBigDecimal(last_balance.toString()));
}

//抓取信用卡可用额度 可提现额度的等一些信息
function crawlLimit( creditCardAllData) {
    creditCardAllData.setBankName("建设银行");
    creditCardAllData.setCardType("信用卡");
    var userInfo = context.get("jsonUserInfo");
    var urlInfo = context.get("jsonUrlInfo");
    var individualUrl = urlInfo.get("P1ACTION").toString();
    var cardNo = creditCardAllData.getFullCardNum();
    var cardUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&isAjaxRequest=true&TXCODE=XE1111&USERID=%s&BRANCHID=%s&SKEY=%s&CrCrd_CardNo=%s";
    cardUrl = String.format(cardUrl, userInfo.getString("USERID"), userInfo.getString("BRANCHID"), userInfo.getString("SKEY"), cardNo);
    var json = ajax_get(cardUrl);
    storeDataToFile(context, json, cardNum + "_card.html")
    if(json.contains("0130Z1108007")){
        logger.error("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 卡信息获取失败,停止抓取");
        return;
    }
    var balanceJson = JSON.parseObject(json);
    //index 0代表人民币额度;index 1代表对应的美元额度
    if (!balanceJson.containsKey("SUCCESS")) {
        return;
    }
    if (balanceJson.get("SUCCESS").toString().equals("true") && balanceJson.containsKey("LIST")) {
        balanceJson = balanceJson.getJSONArray("LIST").getJSONObject(0);
        creditCardAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(balanceJson.getString("CrCrd_CrLine")));  //可用额度
        creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balanceJson.getString("CrCrd_Avl_Lmt_3")));    //余额
        creditCardAllData.setCashLimit(CreditResultUtil.StringToBigDecimal(balanceJson.getString("CrCrd_CshLmt")));    //现金可提取额度
        creditCardAllData.setCardId(UUID.randomUUID().toString());
        creditCardAllData.setNameOnCard(userInfo.getString("NAME"));
    }
}
//抓取未出账单
function crawlUndoneBill( creditCardAllData){
    //创建账单类，并赋已经获取的值
    var billAllData = getBillAllData();
    billAllData.setBankName("建设银行");
    billAllData.setBillType("UNDONE");
    billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
    billAllData.setCashLimit(creditCardAllData.getCashLimit());
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBillMonth(yyyy_MM_PARSER.format(new Date()));
    var userInfo = context.get("jsonUserInfo");
    var urlInfo = context.get("jsonUrlInfo");
    var individualUrl = urlInfo.get("P1ACTION").toString();
    //抓取未出账单信息
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始采集第" + cardNum + "张卡抓取未出账单信息");
    var undoneBillUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl;
    var TXCODE = "XE1146";// 消费记录查询
    var Svc_ID = "1";// 未出账单
    var map = new LinkedHashMap();
    map.put("Svc_ID", Svc_ID);
    map.put("TXCODE", TXCODE);
    map.put("SKEY", userInfo.getString("SKEY"));
    map.put("USERID", userInfo.getString("USERID"));
    map.put("BRANCHID", userInfo.getString("BRANCHID"));
    map.put("CrCrd_CardNo", "all");
    map.put("PAGE_JUMP", "1");
    map.put("Seq_Mod_CgyCd", "01");
    map.put("Seq_MtdCd", "1");
    //发送post请求获取未出账单的TXT
    var unbillHtml = ajax_post(undoneBillUrl, map);
    storeDataToFile(context, unbillHtml, cardNum + "_unbill.txt")
    //如果没有交易明细，继续抓取，如果包含代码"0130Z1109001"或"0130Z1108007"表示会话超时暂处理为抛出异常
    if (unbillHtml.contains("无交易明细记录！")) {
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 抓取第" + cardNum + "张信用卡未出账单无交易明细");
    }else if(unbillHtml.contains("0130Z1109001")||unbillHtml.contains("0130Z1108007")) {
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 抓取第" + cardNum + "张信用卡未出账单无交易明细");
        throw new BankException(BankConstants.BACR_99602_20,"会话超时，请重新登录");
    } else {
        //解析为出账单的TXT信息
        parseUndoneBillForTxt(unbillHtml, billAllData);
        //解析分期信息
        parseInstallMennts(billAllData);
        //计算未出账单的账单金额----本期应还
        computeUnBillBalance(billAllData);
        //计算账单中的新增金额----本期新增
        computeBillCharges(billAllData);
        creditCardAllData.getBills().add(billAllData);
        logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集完毕第" + cardNum + "张卡未出账单信息");
    }
    //由于页面上没有抓取到未出账单的账单日，但是有已出账单的账单日，所以做未出账单日计算
    computeUnbillDate(billAllData);
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " computeUnbillDate计算卡未出账单的账单日月");
}



function parseUndoneBillForTxt(unbillHtml, billAllData) {
    /*未出账单信息TXT的格式为:
     中国建设银行
     中国建设银行信用卡交易明细
     交易日   入账日   信用卡卡号       类型     入账币种   入账金额 交易描述
     已空格分隔
     */
    var strings = unbillHtml.split(/\r\n/g);
    var newStringList = new LinkedList();
    var order_index = 0;
    for each (var mingxi in strings) {
        if (mingxi.trim().length() !== 0) {
            newStringList.add(mingxi.trim().replaceAll(" {2,}", " "));
        }

    }
    for each(var string in newStringList) {
        if (!string.split(" ")[0].match("\\d{8}")) {
            continue;
        }
        var expense = getExpense();
        expense.setId(UUID.randomUUID().toString());
        //交易日期
        var transDate = string.split(" ")[0] !== undefined ? string.split(" ")[0] : ""
        //记账日期
        var postDate = string.split(" ")[1] !== undefined ? string.split(" ")[1] : ""
        //卡号
        var cardFullNo = string.split(" ")[2] !== undefined ? string.split(" ")[2] : ""
        //交易币种
        var currencyType = string.split(" ")[4] !== undefined ? string.split(" ")[4] : ""
        //交易金额 负的代表收入 正的代表支出
        var amountMoney = string.split(" ")[5] !== undefined ? string.split(" ")[5] : ""
        if("元".equals(amountMoney)){
            amountMoney = string.split(" ")[6] !== undefined ? string.split(" ")[6] : ""
        }
        //消费类型
        var remark = string.split(" ")[3] !== undefined ? string.split(" ")[3] : ""
        //交易描述
        var description = "";
        for (var i = 6; i < string.split(" ").length; i++) {
            if ("".equals(description)) {
                description = string.split(" ")[i] !== undefined ? string.split(" ")[i] : ""
            } else {
                description = description + " " + (string.split(" ")[i] !== undefined ? string.split(" ")[i] : "");
            }
        }
        cardFullNo = formatNumber(cardFullNo);
        expense.setTransDate(formatDate(transDate));
        expense.setPostDate(formatDate(postDate));
        expense.setCardNum(cardFullNo.substring(cardFullNo.length() - 4, cardFullNo.length()));
        expense.setDescription(description);
        expense.setCurrencyType(CreditResultUtil.convertCurr(currencyType));
        expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(formatNumber(amountMoney)));
        expense.setCategory(CategoryUtil.getCreditCategory("CCB", description,expense.getAmountMoney().toString()));
        expense.setRemark(remark);
        expense.setOrderIndex(++order_index);
        billAllData.getShoppingSheets().add(expense);
    }

}


/**
 * TXT解析
 */
function parseBillForTxt(billHtml, creditCardAllData){


    var billLines = billHtml.split("\n");
    var lineList = new LinkedList();
    for each (var billLine in billLines) {
        //只保留有明细所在行的信息，去除空格分隔行
        if (billLine.trim().length() !== 0) {
            lineList.add(billLine.trim());
        }
    }
    var monthListMap = new LinkedHashMap();
    var cardNo = "";
    //循环获取的明细集合，如果某一行为空则跳出本次循环，继续解析
    for each (var line in lineList) {
        if (StringUtils.isBlank(line)) {
            continue;
        }
        //TXT格式为
        /*账　　号：4367422434250337268
         开户机构：北京市
         币    种： 人民币
         记账日,交易日期,交易时间,交易地点,支出,收入,账户余额,对方账号,对方户名,币种,摘要
         20170410,20170410,18:05:23,短信服务费,2.00,,31.7,10111000*****7309900900049,对私短信服务费暂挂户,人民币,短信服务费 */
        if (line.contains("：")) {
            var lines = line.split("：");
            if (lines.length == 2) {
                var key = lines[0].replaceAll(" |\\u3000", "").trim();
                var value = lines[1].replaceAll(" |\\u3000", "").trim();
                if (key.contains("账号") && !key.contains(",")) {
                    cardNo = value;
                    creditCardAllData.setFullCardNum(value);
                } else if (key.contains("开户机构")) {
                    creditCardAllData.setOpenBank(value);
                }
            }
        }
        if (line.contains(",")) {
            //账单明细实例:记账日,交易日期,交易时间,交易地点,支出,收入,账户余额,对方账号,对方户名,币种,摘要
            var lines = line.split(",");
            if (lines.length == 11) {
                var flag = lines[0];
                //从明细中可以到交易时间，通过交易时间确定抓到了哪些月份的账单
                if (flag.matches("^[1-9]\\d*$")) {
                    //建设借记卡可以直接下载所查到的账单
                    //把同一个月份的账单放到已月份为Key的map中
                    if (monthListMap.containsKey(flag.substring(0, 6))) {
                        monthListMap.get(flag.substring(0, 6)).add(line);
                    } else {
                        var tempList = new LinkedList();
                        //把明细放到一个临时list中
                        tempList.add(line);
                        monthListMap.put(flag.substring(0, 6), tempList);
                    }
                }
            }
        }
    }
    //卡号后4位
    var cardLastFourNum = "";
    if (cardNo.length() == 19) {
        cardLastFourNum = cardNo.substring(cardNo.length() - 4, cardNo.length());
        creditCardAllData.setFullCardNum(cardNo);
        creditCardAllData.setCardNum(cardLastFourNum);
    }
    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 第" + cardNum + "张借记卡消费明细月份数量" + monthListMap.size());
    //遍历已月份为Key的map，并解析对应月份的明细
    for each(var map in monthListMap.entrySet()) {
        var billAllData = getBillAllData();
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBankName("建设银行");
        billAllData.setBillType("");
        billAllData.setBillMonth(formatMonth(map.getKey()));
        var orderIndex = 0;
        for each(var templine in map.getValue()) {
            var templines = templine.split(",");
            if (templines.length == 11) {
                var expense = getExpense();
                expense.setId(UUID.randomUUID().toString());
                var postDate = templines[0];
                var transDate = templines[1];
                var transTime = templines[2];
                var transAdr = templines[3];
                var zhichu = templines[4];
                var shouru = templines[5];
                var balance = templines[6];
                var oppositeCard = templines[7];
                var oppositeName = templines[8];
                var currecy = templines[9];
                var remark = templines[10];
                expense.setPostDate(formatDate(postDate));
                expense.setTransDate(formatDate(transDate));
                expense.setTransAddr(transAdr);
                if (zhichu.length() > 2) {
                    expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(zhichu));
                }
                if (shouru.length() > 2) {
                    expense.setAmountMoney(CreditResultUtil.StringToBigDecimal("-" + shouru));
                }
                expense.setBalance(CreditResultUtil.StringToBigDecimal(balance));
                expense.setCurrencyType(CreditResultUtil.convertCurr(currecy));
                expense.setOppositeCardNo(oppositeCard);
                expense.setNameOnOppositeCard(oppositeName);
                expense.setRemark(remark);
                expense.setCategory(CategoryUtil.getDebitCategory( remark,expense.getAmountMoney().toString()));
                expense.setOrderIndex(++orderIndex);
                expense.setCardNum(cardLastFourNum);
                expense.setDescription(remark);
                expense.setOppositeBank("");
                expense.setTransChannel("");
                expense.setTransMethod("");
                billAllData.getShoppingSheets().add(expense);
            }
        }
        //billDate为每个月的1号，所以拼接"-01";
        billAllData.setBillDate(formatDate(formatMonth(map.getKey()) + "-01"));
        creditCardAllData.getBills().add(billAllData);
    }
    //如果抓取不足18个月，需要补齐未抓到月份的表头
    if (monthListMap.size() < 18) {
        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 第" + cardNum + "张借记卡消费明细月份数量不足18个月,需人工补齐！！！需人工补齐！！！需人工补齐！！！");
        var monthList = currentSixMonth();
        for each (var month in monthList) {
            if (!monthListMap.containsKey(month)) {
                var billAllData = getBillAllData();
                billAllData.setBillId(UUID.randomUUID().toString());
                billAllData.setBankName("建设银行");
                billAllData.setBillType("");
                billAllData.setBillMonth(formatMonth(month));
                billAllData.setBillDate(formatDate(formatMonth(month) + "-01"));
                creditCardAllData.getBills().add(billAllData);
            }
        }
    }
}

function currentSixMonth() {
    var cal = Calendar.getInstance();
    var sdf = new SimpleDateFormat("yyyyMM");
    var monthList = new ArrayList();
    for (var i = 0; i < 11; i++) {
        var dateString = sdf.format(cal.getTime());
        monthList.add(dateString.substring(0, 6));
        cal.add(Calendar.MONTH, -1);
    }
    return monthList;
}


function crawlDoneBill( creditCardAllData){
    var userInfo = context.get("jsonUserInfo");
    var urlInfo = context.get("jsonUrlInfo");
    var individualUrl = urlInfo.get("P1ACTION").toString();
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始采集第" + cardNum + " 张卡历史账单列表");
    var billListUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&USERID=%s&BRANCHID=%s&SKEY=%s&TXCODE=XE1140";
    billListUrl = String.format(billListUrl, userInfo.getString("USERID"), userInfo.getString("BRANCHID"), userInfo.getString("SKEY"));
    var billListHtml = ajax_get(billListUrl);
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集完毕第" + cardNum + " 张卡历史账单列表");
    storeDataToFile(context, billListHtml, cardNum + "_donebill_list.html")
    //判断页面中是否有历史账单列表
    if (!billListHtml.contains("历史账单列表")) {
        if (billListHtml.contains("XDBA02811022")||billListHtml.contains("YDCA02811101")) {
            logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集第" + cardNum + "历史账单列表失败:没有可以查询的数据!");
        } else {
            logger.error("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集第" + cardNum + "历史账单列表失败,停止抓取");
            return;
        }
    } else {
        var doc = Jsoup.parse(billListHtml);
        var trs = doc.select("#result > tbody >tr");
        //解析获取id为result的table中的tr，历史记录月份信息从第三个tr开始，头两行为标题
        if (trs.size() < 2) {
            logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 该用户无历史消费记录，停止抓取");
            return;
        }
        var param = new LinkedHashMap();
        param.put("yzacc","");
        param.put("yzflag","1");
        param.put("yztxcode","");
        param.put("flagnext","1");
        param.put("SMSCODE_FRTCTRL","");
        param.put("SKEY", doc.select("[name = SKEY]").val());
        param.put("USERID", doc.select("[name = USERID]").val());
        param.put("BRANCHID", doc.select("[name = BRANCHID]").val());
        param.put("TXCODE","XE1144");
        param.put("CrCrd_Acg_Setl_Dt", "");
        param.put("StDt", doc.select("[name = StDt]").val());
        param.put("Prd_Num", doc.select("[name = Prd_Num]").val());
        param.put("clientFileName", "");
        param.put("type","1");

        //点击下载12个月的已出账单 建设官网只提供12个月的账单下载
        var billUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl;
        var BlDate = "";
        //如果查询到多与12个月的账单，则循环12个月的，如果少于12个月账单，则可以全部下载并解析
        for (var i = 1; i <= 12 && i < trs.size(); i++) {
            var tds = trs.get(i).select("td");
            var billDateP = tds.get(0).text().trim();
            if("".equals(BlDate)){
                //抓取账单日
                BlDate = billDateP;
                logger.info("任务【{}】，输出BlDate的值{}",context.get(LUA_TASK_KEY),BlDate);
            }
            var data = billDateP.replaceAll("-","");
            param.put("CrCrd_Acg_Setl_Dt", data);
            logger.info("任务【{}】，输出建设时间data{}",context.get(LUA_TASK_KEY),data);
            //param.put("clientFileName", formatNumber(date) + ".txt");
            param.put("clientFileName", "信用卡对账单.txt");
            //创建本期账单开始填充数据
            var billAllData = getBillAllData();
            try {
                logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始采集" + cardNum + "张卡第" + i + "个已出账单消费明细获取成功");
                var billTxt = ajax_post(billUrl, param);
                storeDataToFile(context, billTxt, "第" + cardNum + "张卡第" + i + "个已出账单消费明细.txt")
                if (StringUtils.isBlank(billTxt)) {
                    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集失败" + cardNum + "张卡第" + i + "个已出账单消费明细");
                    continue;
                }
                logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 采集完毕" + cardNum + "张卡第" + i + "个已出账单消费明细");
                parseDoneBillTxt(billTxt, billAllData);
            } catch (e) {
                statCaughtException(context, e);
                // throw new BankException(BankConstants.BACR_20306_30, "解析第" + cardNum + "张第" + i + "个月份消费明细失败");
            }
            //解析分期明细
            parseInstallMennts(billAllData);
            //计算账单中的新增金额----本期新增
            computeBillCharges(billAllData);
            creditCardAllData.getBills().add(billAllData);
            //抓取到的账单日和还款日放在context中，用于计算未出账单账单日和还款日
            if(i==1) {
                context.put("billDate", billAllData.getBillDate());
                context.put("payDueDate", billAllData.getPaymentDueDate());
            }
        }
        //如果tr>13则还可以抓取12个月之前不能下载表头，只有明细的账单，请求页面，用Jsoup抓取
        //近一年数据为之前开发，后来要求最多抓取3年数据，做新分支处理，所以没有统一处理
        if(trs.size()>13){
            var data = new LinkedHashMap();
            data.put("SKEY", userInfo.getString("SKEY"));
            data.put("USERID", userInfo.getString("USERID"));
            data.put("BRANCHID", userInfo.getString("BRANCHID"));
            data.put("TXCODE", "XE1142");
            data.put("clientFileName", "");
            for(var i = 13;i<trs.size();i++){
                var billAllData = getBillAllData();
                data.put("Prd_Num", Integer.parseInt(i));
                setPostData(data,trs.get(i));
                var billInfoHtml = ajax_post(billUrl, data);
                storeDataToFile(context, billInfoHtml, "第" + cardNum + "张卡第" + i + "个已出账单消费明细.html")
                //Jsoup解析明细页面
                parseDoneBillHtml(billInfoHtml,billAllData);
                creditCardAllData.getBills().add(billAllData);
                //解析每月账单


            }
            //抓取近12个月之前所有明细
            var params = new LinkedHashMap();
            params.put("SKEY", userInfo.getString("SKEY"));
            params.put("USERID", userInfo.getString("USERID"));
            params.put("BRANCHID", userInfo.getString("BRANCHID"));
            params.put("TXCODE", "XE1146");
            params.put("CrCrd_CardNo", "all");
            params.put("Seq_Mod_CgyCd", "01");
            params.put("PAGE_JUMP", "1");
            params.put("Seq_MtdCd", "1");
            params.put("Svc_ID", "0");
            params.put("START_DATE", getStartDate(BlDate));
            params.put("END_DATE", getEndDate(BlDate));
            params.put("clientFileName", "");
            params.put("STS_TRACE_ID", "");
            params.put("Flt_Acc_SN", "");
            params.put("Flt_Inf_TnCcy_Cd", "");
            params.put("Flt_Txn_Tp_Nm", "");
            params.put("Flt_Prty_Nm_Adr", "");
            params.put("Flt_Txn_Nm_Dsc", "");
            var billForTxt = ajax_post(billUrl, params);
            storeDataToFile(context, billForTxt, cardNum + "_doneBillBefore.txt")
            //解析12个月之前明细信息
            parseDoneBillForTxt(billForTxt,creditCardAllData);

        }
    }
}

function parseDoneBillForTxt(billForTxt, creditCardAllData){
    /*TXT明细格式为
     中国建设银行
     中国建设银行信用卡交易明细
     交易日   入账日   信用卡卡号       类型     入账币种   入账金额 交易描述
     20180221 20180221 6253624048856148 存入     人民币        -6.00 支付宝还款     1897022180764970523
     */
    logger.info("任务【 {} 】 billForTxt {}", context.get(LUA_TASK_KEY), billForTxt)
    var strings = billForTxt.split(/\r\n/g);
    var newStringList = new LinkedList();
    var order_index = 0;
    var index = 12;
    var billAllData = creditCardAllData.getBills().get(index);
    for each (var sss in strings) {
        if (sss.trim().length() !== 0) {
            newStringList.add(sss.trim().replaceAll(" {2,}", " "));
        }
    }
    var date = getNextBillDate(creditCardAllData.getBills().get(index).getBillDate());
    for each (var string in newStringList) {
        if (!string.split(" ")[0].match("\\d{8}")) {
            continue;
        }
        var expense = getExpense();
        expense.setId(UUID.randomUUID().toString());
        //交易日期
        var transDate = string.split(" ")[0] === undefined ? "" : string.split(" ")[0]
        logger.info("任务【 {} 】 transDate {}", context.get(LUA_TASK_KEY), transDate)
        //记账日期
        var postDate = string.split(" ")[1] === undefined ? "" : string.split(" ")[1]
        logger.info("任务【 {} 】 postDate {}", context.get(LUA_TASK_KEY), postDate)
        //卡号
        var cardFullNo = string.split(" ")[2] === undefined ? "" : string.split(" ")[2]

        logger.info("任务【 {} 】 cardFullNo {}", context.get(LUA_TASK_KEY), cardFullNo)
        //交易币种
        var currencyType = string.split(" ")[4] === undefined ? "" : string.split(" ")[4]
        logger.info("任务【 {} 】 currencyType {}", context.get(LUA_TASK_KEY), currencyType)
        //交易金额 负的代表收入 正的代表支出
        var amountMoney = string.split(" ")[5] === undefined ? "" : string.split(" ")[5]
        logger.info("任务【 {} 】 amountMoney {}", context.get(LUA_TASK_KEY), amountMoney)
        //消费类型
        var remark = string.split(" ")[3] === undefined ? "" : string.split(" ")[3]
        logger.info("任务【 {} 】 remark {}", context.get(LUA_TASK_KEY), remark)
        //交易描述
        var description = "";
        for (var i = 6; i < string.split(" ").length; i++) {
            if ("".equals(description)) {
                description = string.split(" ")[i];
            } else {
                description = description + " " + (string.split(" ")[i] === undefined ? "" : string.split(" ")[i]);
            }
        }
        cardFullNo = formatNumber(cardFullNo);
        expense.setTransDate(formatDate(transDate));
        expense.setPostDate(formatDate(postDate));
        expense.setCardNum(cardFullNo.substring(cardFullNo.length() - 4, cardFullNo.length()));
        expense.setDescription(description);
        expense.setCurrencyType(CreditResultUtil.convertCurr(currencyType));
        expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(formatNumber(amountMoney)));
        expense.setCategory(CategoryUtil.getCreditCategory("CCB", description, amountMoney));
        expense.setRemark(remark);
        //判断交易日和账单日的的大小，如果到一个新的月份，则order_index置为0，获取已经抓取到的下一个月份的billAllData
        if(index+1<creditCardAllData.getBills().size()&&expense.getPostDate().compareTo(date)<=0){
            order_index = 0;
            //当当前expense明细的日期
            do {
                billAllData = creditCardAllData.getBills().get(++index);
                //获取下一个账单日
                date = getNextBillDate(date);
            } while (expense.getPostDate().compareTo(date)<0);
        }
        expense.setOrderIndex(++order_index);
        billAllData.getShoppingSheets().add(expense);
    }
    //前12个月已做过分期和处理本期新增处理，此处只处理12个月之前的
    for(var i=12;i<creditCardAllData.getBills().size();i++){
        parseInstallMennts(creditCardAllData.getBills().get(i));
        computeBillCharges(creditCardAllData.getBills().get(i));
    }

}

function getNextBillDate(date){
    /*var sdf = new SimpleDateFormat("yyyy-MM-dd");
     var billDate = sdf.parse(date);*/
    var cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, -1);
    date = cal.getTime();
    return date;
}

function parseDoneBillHtml(billInfoHtml,billAllData) {
    var doc = Jsoup.parse(billInfoHtml);
    var trs = doc.select("#result2").select("tr");
    var billDate = doc.select("#result1 > tbody > tr > td > span:nth-child(2)").select("script").html();
    var repaymentDate = doc.select("#result1 > tbody > tr > td > span:nth-child(3)").select("script").html();
    if(trs.size()>1){
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBankName("建设银行");
        billAllData.setBillType("DONE");
        billAllData.setBillDate(formatDate(billDate));                                 //账单月份
        billAllData.setBillMonth(formatMonth(billDate));
        billAllData.setPaymentDueDate(formatDate(repaymentDate));
        for(var i = 1;i<trs.size();i++){
            var tds = trs.get(i).select("td");
            if(tds.get(0).text().contains("人民币")){
                billAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(getStringDecimal(3,tds)));
                billAllData.setCashLimit(CreditResultUtil.StringToBigDecimal(getStringDecimal(4,tds)));
                billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal(getStringDecimal(1,tds)));
                billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal(getStringDecimal(7,tds)));
                billAllData.setMinPayment(CreditResultUtil.StringToBigDecimal(getStringDecimal(2,tds)));
            }else if(tds.get(0).text().contains("美元")){
                billAllData.setUsdCreditLimit(CreditResultUtil.StringToBigDecimal(getStringDecimal(3,tds)));
                billAllData.setUsdCashLimit(CreditResultUtil.StringToBigDecimal(getStringDecimal(4,tds)));
                billAllData.setUsdNewBalance(CreditResultUtil.StringToBigDecimal(getStringDecimal(1,tds)));
                billAllData.setUsdLastBalance(CreditResultUtil.StringToBigDecimal(getStringDecimal(7,tds)));
                billAllData.setUsdMinPayment(CreditResultUtil.StringToBigDecimal(getStringDecimal(2,tds)));
            }
        }
    }

}
function getStringDecimal(index,tds){
    return tds.get(index).select("script").html().substring(tds.get(index).select("script").html().indexOf("('")+2,tds.get(index).select("script").html().indexOf(("')")));
}

function setPostData(data, tr){
    var tds = tr.select("td");
    var BlDay = tds.get(0).text().trim();
    var startDate = getPostStartDate(BlDay);
    var endDate = getPostEndDate(BlDay);
    data.put("CrCrd_Acg_Setl_Dt", endDate);
    data.put("StDt", startDate);
}

function getPostEndDate(blDay) {
    return blDay.replaceAll("-", "");
}

function getPostStartDate(BlDate){
    var sdf = new SimpleDateFormat("yyyy-MM-dd");
    var sdf1 = new SimpleDateFormat("yyyyMMdd");
    var date = sdf.parse(BlDate);
    var cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, -1);
    cal.add(Calendar.DATE, 1);
    var startDate = sdf1.format(cal.getTime());
    return startDate;
}

function getStartDate( BlDate){
    var sdf = new SimpleDateFormat("yyyy-MM-dd");
    var sdf1 = new SimpleDateFormat("yyyyMMdd");
    var date = sdf.parse(BlDate);
    var cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.YEAR, -2);
    cal.add(Calendar.DATE, 1);
    var startDate = sdf1.format(cal.getTime());
    return startDate;
}

function getEndDate( BlDate) {
    var sdf = new SimpleDateFormat("yyyy-MM-dd");
    var sdf1 = new SimpleDateFormat("yyyyMMdd");
    var date = sdf.parse(BlDate);
    var cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.YEAR, -1);
    var startDate = sdf1.format(cal.getTime());
    return startDate;
}

function parseDoneBillTxt(billTxt,billAllData){
    /*下载账单的格式为
     中国建设银行
     中国建设银行信用卡对账单(Credit Card Statement)
     客户姓名 徐万海
     本期账单日(Current Statement Date) 20180107
     账单周期(Account Cycle)        20171208-20180107
     本期到期还款日(Current Payment Due Date) 20180127
     授信额度(Credit Limit)         30000.00
     取现额度(Cash Advance Limit)   15000.00
     截止本期账单日可用额度 29142.73
     本期全部应还款额(New Balance)  争议款/笔数(Dispute Amt/Nbr)
     人民币(CNY) 857.27             0.00/0
     美  元(USD) 0.00               0.00/0
     本期最低还款额(Min.Payment)
     人民币(CNY) 200.00
     美  元(USD) 0.00
     专项分期剩余总额度 0.00
     应还款明细（“应还款额/溢缴款”为负数，表示账户有溢缴款）
     信用卡卡号(Card Number) 账户币种(Currency) 应还款额/溢缴款(New Balance) 最低还款额(Min.Payment)
     9389                    人民币(CNY)                         857.27               200.00
     交易明细
     交易日   记账日   卡号后四位 交易币种/金额    结算币种/金额       交易描述
     人民币账户(RMB Account) 上期账单日余额(Previous Balance) 3166.00
     20171208 20171208 9389       CNY/3.00         人民币/3.00         龙卡安心用增值服务费
     */
    var mingxis = billTxt.split(/\r\n/g);
    var newStringList = new LinkedList();
    for each (var mingxi in mingxis) {
        if (mingxi.trim().length() !== 0) {
            newStringList.add(mingxi.trim().replaceAll(" {2,}", " "));
        }
    }
    billAllData.setBankName("建设银行");
    billAllData.setBillType("DONE");
    billAllData.setBillId(UUID.randomUUID().toString());
    var pay_due_date = "";
    for (var index = 0; index < newStringList.size(); index++) {
        var eachString = newStringList.get(index);
        if (eachString.startsWith("本期账单日")) {
            var billDate = eachString.split("\)")[1];
            var billMonth = billDate;
            billAllData.setBillDate(formatDate(billDate));                                 //账单月份
            billAllData.setBillMonth(formatMonth(billMonth));                               //账单日
        } else if (eachString.startsWith("本期到期还款日")) {
            if (eachString.contains("已逾期")) {
                if(StringUtils.isNotBlank(pay_due_date)){
                    var paymentdate = billMonth + "-" +pay_due_date;
                    billAllData.setPaymentDueDate(formatDate(paymentdate.replaceAll("-","")));
                }else{
                    var paymentdate = billMonth + "-22"
                    billAllData.setPaymentDueDate(formatDate(paymentdate.replaceAll("-","")));
                }

            } else {
                var repaymentDate = eachString.split("\)")[1];
                billAllData.setPaymentDueDate(formatDate(repaymentDate));//账单月份
                //截取还款日
                pay_due_date = repaymentDate.substring(repaymentDate.length-2,repaymentDate.length);
            }
        } else if (eachString.startsWith("授信额度")) {
            var creditLimit = eachString.split("\)")[1];
            billAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(creditLimit));
        } else if (eachString.startsWith("取现额度")) {
            var cashLimit = eachString.split("\)")[1];
            billAllData.setCashLimit(CreditResultUtil.StringToBigDecimal(cashLimit));
        } else if (eachString.startsWith("本期全部应还款额")) {
            var tempString = "";
            var tempIndex = index;
            while (!tempString.startsWith("本期最低还款额")) {
                if (tempString.startsWith("人民币")) {
                    var newBalance = tempString.split(" ")[1];
                    billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal(newBalance));
                } else if (tempString.startsWith("美 元")) {
                    var usdNewBalance = tempString.split(" ")[2];
                    billAllData.setUsdNewBalance(CreditResultUtil.StringToBigDecimal(usdNewBalance));
                }
                tempString = newStringList.get(++tempIndex);
            }
        } else if (eachString.startsWith("本期最低还款额")) {
            var tempString = "";
            var tempIndex = index;
            while (!tempString.startsWith("应还款明细")) {
                if (tempString.startsWith("人民币")) {
                    var minRepayment = tempString.split("\)")[1];
                    billAllData.setMinPayment(CreditResultUtil.StringToBigDecimal(minRepayment));
                } else if (tempString.startsWith("美 元")) {
                    var usdMinRepayment = tempString.split("\)")[1];
                    billAllData.setUsdMinPayment(CreditResultUtil.StringToBigDecimal(usdMinRepayment));
                }
                tempString = newStringList.get(++tempIndex);
            }
        } else if (eachString.contains("人民币账户") && eachString.contains("上期账单日余额")) {
            var lastBalance = eachString.split("\)")[2];
            billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal(lastBalance));             //上期余额
        } else if (eachString.contains("美元账户") && eachString.contains("上期账单日余额")) {
            var usdNewBalance = eachString.split("\)")[2];
            billAllData.setUsdLastBalance(CreditResultUtil.StringToBigDecimal(usdNewBalance));
        } else if (eachString.startsWith("交易明细")) {
            try {
                parseDoneBillExpenseForTxt(newStringList.indexOf(eachString), newStringList, billAllData);
                logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析" + billAllData.getBillMonth() + "月份账单详情页成功，继续抓取");
            } catch (e) {
                // statCaughtException(context, e);
                logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + "解析" + billAllData.getBillMonth() + "月份的第账单详情出错,停止解析,继续抓取", e);
                throw new BankException(BankConstants.BACR_20306_30, "解析消费明细失败");
            }
        }
    }
}


function crawlDeposit(creditCardAllData,param) {
    logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + "开始抓取账户存款信息");
    //声明Json对象，存储基本信息
    var basicInfo = context.get("jsonUserInfo");
    var urlInfo = context.get("jsonUrlInfo");
    var cardNo = creditCardAllData.getFullCardNum();
    var individualUrl = urlInfo.getString("P1ACTION");
    //拼接获取账户信息的url
    var depositCardUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl + "&ROW_NO=3&BRANCHID=%s&SKEY=%s&USERID=%s&ACC_NO=%s&BBANK_NAME=%s&ACC_SIGN=%s&FLAG_CARD=4&TXCODE=310800";
    depositCardUrl = String.format(depositCardUrl, basicInfo.getString("BRANCHID"), basicInfo.getString("SKEY"), basicInfo.getString("USERID"), cardNo, basicInfo.getString("BRANCHID"), cardNo);
    param.put("queryyzacc", cardNo);
    param.put("yzacc", cardNo);
    logger.info("CCB 建设银行 taskkey: {} ,抓取deposit请求开始",context.get(Constants.LUA_TASK_KEY));
    var depositCardHtml = ajax_post(depositCardUrl, param);
    logger.info("CCB 建设银行 taskkey: {} ,抓取deposit请求结束",context.get(Constants.LUA_TASK_KEY));
    //如果请求返回html中包含 “0130Z1108007”或“0130Z1109001”则页面表现为 “暂不能处理您的请求，请重新登录” 则不能继续抓取，抛出异常会话超时
    if(!depositCardHtml.contains("0130Z1108007")&&!depositCardHtml.contains("0130Z1109001")){
        storeDataToFile(context, depositCardHtml, cardNum + "_deposits_1.html")
        var deposits = new ArrayList();
        //解析获取到的html页面
        var doc = Jsoup.parse(depositCardHtml);
        logger.info("CCB 建设银行 taskkey: {} ,jsoup解析页面",context.get(Constants.LUA_TASK_KEY));
        var trs = doc.select("#result > tbody:nth-child(1)> tr");
        for (var index = 0; index < trs.size(); index++) {
            var deposit = getCreditCardTimeDeposit();
            var tds = trs.get(index).select("td");
            var despoitDate = (tds.get(1).text());
            var depositType = tds.get(2).text();
            var currency = tds.get(3).text();
            var balance = tds.get(4).attr("title").split(":")[1];
            deposit.setDepositDate(formatDate(despoitDate));
            deposit.setCurrencyType(CreditResultUtil.convertCurr(currency));
            deposit.setBalance(CreditResultUtil.StringToBigDecimal(balance));
            //根据账户存款类型判断存款年月以及利率
            judgeDepositType(depositType, tds, deposit);
            creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance));
            deposits.add(deposit);
        }
        creditCardAllData.setDeposits(deposits);
    }else{
        logger.error("CCB 建设银行 taskkey: {} ,抓取deposit会话超时，页面为：{}",context.get(Constants.LUA_TASK_KEY),depositCardHtml);
        throw new BankException(BankConstants.BACR_99602_20,"会话超时，请重新登录");
    }
}


/**
 * 根据账户存款类型判断存款年月以及利息	整存整取 三个月 (利率:1.35%)
 */
function judgeDepositType(depositType, tds, deposit) {
    if (depositType.contains("活期储蓄")) {
        deposit.setDepositType(depositType);
    } else if (depositType.contains("整存整取")) {
        deposit.setDepositType("整存整取");
        //目前整存整取是有利息信息的 后续可能出现多种情况
        var insertScript = tds.get(2).select("script").first().data();
        if (StringUtils.isNotBlank(insertScript)) {
            var insert = String.valueOf(Double.parseDouble(formatNumber("1.35000")) / 100).substring(0, 6);
            deposit.setInterest(CreditResultUtil.StringToBigDecimal(insert));
        }
        //针对三个月,三年等情况进行的处理
        var despoitTypeTime = depositType.split(" ")[1];
        var despoitDate = deposit.getDepositDate();
        if (despoitTypeTime.contains("月")) {
            var index = despoitTypeTime.indexOf("个");
            var monthNum = despoitTypeTime.substring(0, index);
            var period = basicConvert(monthNum);
            var duedate = addDueDate("MONTH", period, despoitDate);
            deposit.setPeriod(period);
            deposit.setPeriodUnit("MONTH");
            deposit.setDueDate(duedate);
        } else {
            if (despoitTypeTime.contains("年")) {
                var index = despoitTypeTime.indexOf("年");
                var yearNum = despoitTypeTime.substring(0, index);
                if (yearNum.equals("半")) {
                    var period = 6;
                    var duedate = addDueDate("MONTH", period, despoitDate);
                    deposit.setPeriod(period);
                    deposit.setPeriodUnit("MONTH");
                    deposit.setDueDate(duedate);
                } else {
                    var period = basicConvert(yearNum);
                    var duedate = addDueDate("YEAR", period, despoitDate);
                    deposit.setPeriod(period);
                    deposit.setPeriodUnit("YEAR");
                    deposit.setDueDate(duedate);
                }
            }
        }
    }

}


function basicConvert(num) {
    var intNum = 0;
    if ("一".equals(num)) {
        intNum = 1;
    } else if ("二".equals(num)) {
        intNum = 2;
    } else if ("三".equals(num)) {
        intNum = 3;
    } else if ("四".equals(num)) {
        intNum = 4;
    } else if ("五".equals(num)) {
        intNum = 5;
    } else if ("六".equals(num)) {
        intNum = 6;
    } else if ("七".equals(num)) {
        intNum = 7;
    } else if ("八".equals(num)) {
        intNum = 8;
    } else if ("九".equals(num)) {
        intNum = 9;
    } else if ("十".equals(num)) {
        intNum = 10;
    } else if ("十一".equals(num)) {
        intNum = 11;
    } else if ("十二".equals(num)) {
        intNum = 12;
    }
    return intNum;
}

/**
 * 根据给出的是月份还是年份来确定
 *
 * @param flag        YEAR  MONTH
 * @param period      三
 * @param depositDate 2017-07-13
 * @return
 */
function addDueDate(flag,period,depositDate) {
    //即  2017-07-03
    depositDate = yyyy_MM_dd_PARSER.format(depositDate);
    var yearMonthDay = depositDate.split("-");
    var due_date = "";
    if ("YEAR".equals(flag)) {
        var newYear = Integer.parseInt(yearMonthDay[0]) + period;
        due_date = newYear + "-" + yearMonthDay[1] + "-" + yearMonthDay[2];
    }
    if ("MONTH".equals(flag)) {
        var newMonth = Integer.parseInt(yearMonthDay[1]) + period;
        if (newMonth > 12) {
            newMonth = newMonth%12;
            var newYear = Integer.parseInt(yearMonthDay[0]) + 1;
            yearMonthDay[0] = Integer.toString(newYear);
        }
        var newMonthString = "";
        if(Integer.parseInt(newMonth).toString().length==1){
            newMonthString = "0"+newMonth;
        }else{
            newMonthString = ""+newMonth;
        }
        due_date = yearMonthDay[0] + "-" + newMonthString + "-" + yearMonthDay[2];
    }
    return yyyy_MM_dd_PARSER.parse(due_date);
}

/**
 * @param index      交易明细的index +3是交易明细具体数据体现
 * @param stringList string line集合
 *                   已出账单消费明细TXT解析
 */
function parseDoneBillExpenseForTxt(index,stringList,billAllData) {
    var expenseList = new LinkedList();
    var order_index = 0;
    for (var i = index + 3; i < stringList.size(); i++) {
        var data = stringList.get(i).split(" ");
        if (data.length >= 6) {
            // 交易日期
            var tranDate = data[0].trim();
            // 记账日期
            var recordDate = data[1].trim();
            if (StringUtils.isBlank(tranDate) && StringUtils.isBlank(recordDate)) {
                return;
            }
            //判读是否是消费明细 有的卡最后一行是美元账户上期余额
            if (!tranDate.matches("^[1-9]\\d*$") && !recordDate.matches("^[1-9]\\d*$")) {
                return;
            }
            // 卡号后四位
            var cardNo = data[2].replaceAll("/扫码","");
            // 交易币种
            var transCurrency = data[3].split("/")[0];// 无script标签
            if(equals("",transCurrency)){
                transCurrency = "OTHER";
            }
            // 交易金额
            var transAmount = data[3].split("/")[1];
            // 交易说明
            var transRemark = "";
            if (data.length > 6) {
                var buffer = new StringBuffer();
                for (var j = 5; j < data.length; j++) {
                    buffer.append(data[j]);
                }
                transRemark = buffer.toString();
            } else {
                transRemark = data[5];
            }
            tranDate = formatDate(tranDate);
            recordDate = formatDate(recordDate);
            transAmount = formatNumber(transAmount);
            var expense = getExpense();                                                //shopping_sheets类账单的明细
            expense.setId(UUID.randomUUID().toString());                                    //页面没有
            expense.setCardNum(cardNo);                                                    //卡号后四位
            expense.setTransDate(tranDate);                                  //格式化交易日期
            expense.setPostDate(recordDate);                                               //记账日期
            expense.setDescription(transRemark);                                            //交易说明
            expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(transAmount));      //交易金额
            expense.setCurrencyType(transCurrency);                                        //交易币种
            expense.setCategory(CategoryUtil.getCreditCategory("CCB", transRemark, transAmount));    //判断消费类型
            expense.setOrderIndex(++order_index);                                          //消费详情序号
            expenseList.add(expense);
            billAllData.setShoppingSheets(expenseList);
        }
    }
}

/**
 * 计算分期的方法
 */
function parseInstallMennts(billAllData) {
    var expenseList = billAllData.getShoppingSheets();
    var installmentList = null;
    if (billAllData.getInstallments() == null) {
        installmentList = new ArrayList();
    } else {
        installmentList = billAllData.getInstallments();
    }
    //分期手续费
    var handExpenseList = new LinkedList();
    //分期金额
    var needHandExpenseList = new LinkedList();
    for (var i = 0; i < expenseList.size(); i++) {
        var expense = expenseList.get(i);
        var description = expense.getDescription();
        //判断是否是分期账单
        if (description.contains("转分期付款")  || description.contains("分期乐")) {
            continue;
        } else if (description.replace(/\s+/g,"").contains("*金额") || description.replace(/\s+/g,"").contains("分期*") || description.replace(/\s+/g,"").contains("现金分期*") || description.replace(/\s+/g,"").contains("账单分期*")) {
            continue;
        } else if (description.contains("返现")) {
            continue;
        } else if ((description.contains("分期") && description.contains("手续费")) || (description.contains("等额还款") && description.contains("手续费"))) {
            handExpenseList.add(expense);
            continue;
        } else if ((description.contains("分期") && !description.contains("手续费")) || (description.contains("等额还款") && !description.contains("手续费"))) {
            needHandExpenseList.add(expense);
            continue;
        }
    }
    try {
        if (handExpenseList.size() == 0) {
            logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张卡" + billAllData.getBillMonth() + "的账单无手续费分期情况");
        }
        if (needHandExpenseList.size() == 0) {
            logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张卡" + billAllData.getBillMonth() + "的账单无分期情况");
        }
    } catch (e) {
        // statCaughtException(context, e);
        logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张卡" + billAllData.getBillMonth() + "的分期,List排序出错", e);
    }
    if (handExpenseList.size() > needHandExpenseList.size()) {
        logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 解析第" + cardNum + "张卡" + billAllData.getBillMonth() + "的分期,分期手续费List长度大于具体分期情况List,不符合正常情况");
    }
    if (needHandExpenseList.size() > 0) {
        for (var index = 0; index < needHandExpenseList.size(); index++) {
            var expense = needHandExpenseList.get(index);
            var description = expense.getDescription();
            try {
                var installment = getInstallment();
                installment.setPostDate(expense.getPostDate());
                installment.setTransDate(expense.getTransDate());
                installment.setInstallmentDesc(description);
                if (description.contains("/")) {
                    //从描述中取到总期数
                    installment.setTotalMonth(Integer.parseInt(description.substring(description.indexOf("/") + 1, description.length())));
                    if(description.contains("分期")&&description.contains(":借记卡")){
                        //从描述中获取到当前期数
                        installment.setCurrentMonth(Integer.parseInt(description.substring(description.indexOf(":借记卡") + 9, description.indexOf("/"))));
                    } else if (description.contains("分期") && description.contains("账单 ")) {
                        installment.setCurrentMonth(Integer.parseInt(description.substring(description.indexOf("账单 ") + 3, description.indexOf("/"))));
                    }else if (description.contains("等额还款") && description.contains("账单")){
                        var tempDesc = description.replace(/\s+/g,"")
                        installment.setCurrentMonth(Integer.parseInt(tempDesc.substring(tempDesc.indexOf("账单") + 2, tempDesc.indexOf("/"))));
                    } else {
                        //等额还款单期金额170314账单01/12
                        //从描述中获取到当前期数
                        installment.setCurrentMonth(Integer.parseInt(description.substring(description.indexOf(":分期") + 3, description.indexOf("/"))));
                    }
                }
                installment.setCurrencyType(expense.getCurrencyType());
                installment.setAmountMoney(expense.getAmountMoney());
                if(description.contains("现金")){
                    installment.setInstallmentType("CASH");
                }else{
                    installment.setInstallmentType("BILL");
                }
                if (index < handExpenseList.size()) {
                    var handExpense = handExpenseList.get(index);
                    var newDescription = handExpense.getDescription();
                    if (newDescription.contains("手续费")) {
                        //设置手续费信息
                        installment.setHandingFee(handExpense.getAmountMoney());
                        installment.setHandingfeeDesc(newDescription);
                    }
                }
                installment.setBillId(billAllData.getBillId());
                installment.setShoppingsheetId(expense.getId());
                installmentList.add(installment);
                billAllData.setShoppingSheets(expenseList);
                billAllData.setInstallments(installmentList);
            } catch (e) {
                statCaughtException(context, e);
                logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 匹配第" + cardNum + "张卡" + billAllData.getBillMonth() + "的分期出错", e);
            }
        }
    }
}



// 计算未出账单的账单日、账单月
function computeUnbillDate( billAllData) {

    var billDate =  context.get("billDate");
    var payDueDate = context.get("payDueDate");
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " computeUnbillDate计算卡未出账单的账单日月开始");
    //抓取到非空的billDate和payDueDate则把时间往后推一个月
    if(billDate!=null&&payDueDate!=null) {
        try {
            var calendar = Calendar.getInstance();
            calendar.setTime(billDate);
            calendar.add(Calendar.MONTH, 1);// 把日期往后增加一个月.整数往后推,负数往前移动
            billDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
            var billMonth = DateFormatUtils.format(billDate, "yyyy-MM");
            var newPaymentDate = null;
            if (payDueDate != null) {
                calendar.setTime(payDueDate);
                calendar.add(Calendar.MONTH, 1);
                newPaymentDate = calendar.getTime();
            }
            billAllData.setBillDate(billDate);
            billAllData.setBillMonth(billMonth);
            billAllData.setPaymentDueDate(newPaymentDate);
        } catch (e) {
            statCaughtException(context, e);
            logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + "解析日期格式出错" + billDate, e);
        }
    }else {
        var date = new Date();
        var calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);// 把日期往后增加一个月.整数往后推,负数往前移动
        date = calendar.getTime(); // 这个时间就是日期往后推一天的结果
        var billMonth = DateFormatUtils.format(date, "yyyy-MM");
        billAllData.setBillMonth(billMonth);
        billAllData.setPaymentDueDate(date);
    }
}

// 计算未出账单的账单金额----本期应还
function computeUnBillBalance(billAllData) {
    var balance = new BigDecimal(0);
    var expenses = billAllData.getShoppingSheets();
    if (expenses.size() == 0) {
        return;
    }
    for (var i = 0; i < expenses.size(); i++) {
        var expense = expenses.get(i);
        //消费明细里面正的代表支出 负的目前是上期还款
        if (expense.getAmountMoney() !== null) {
            balance = balance.add(expense.getAmountMoney().abs());
        }
    }
    billAllData.setNewBalance(balance);
}

// 计算账单中的新增金额----本期新增
function computeBillCharges(billAllData) {
    var charges = new BigDecimal(0);
    var lastPayment = new BigDecimal(0);
    var expenses = billAllData.getShoppingSheets();
    if (expenses.size() == 0) {
        return;
    }
    for (var i = 0; i < expenses.size(); i++) {
        var expense = expenses.get(i);
        //消费明细里面正的代表支出 负的目前是上期还款
        if (expense.getAmountMoney() !== null) {
            if (expense.getAmountMoney().compareTo(new BigDecimal(0)) == 1) {
                charges = charges.add(expense.getAmountMoney().abs());
            }else{
                lastPayment = lastPayment.add(expense.getAmountMoney());
            }
        }
    }
    billAllData.setNewCharges(charges);
}


/**
 * 要获取开始和结束的时间建设借记卡支持查询6个月的 所以起止时间为20170301-20170805
 *
 * @return
 */
function getStartAndEndDate() {
    var dateMap = new LinkedHashMap();
    var format = new SimpleDateFormat("yyyyMMdd");
    var calendar = Calendar.getInstance();
    var endDate = format.format(calendar.getTime());
    calendar.add(Calendar.MONTH, -17);
    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
    var beginDate = format.format(calendar.getTime());
    dateMap.put("beginDate", beginDate);
    dateMap.put("endDate", endDate);
    return dateMap;
}



/**
 * 下载账单明细EXCEL/TXT
 *
 * @param spanIndex 每张借记卡的明细URL 在span标签里面
 */
function downloadBill(spanIndex,creditCardAllData)  {
    //获取一些基本参数信息
    var cardNo = creditCardAllData.getFullCardNum();
    var cardFourNo = creditCardAllData.getCardNum();
    var urlInfo = context.get("jsonUrlInfo");
    var individualUrl = urlInfo.getString("P1ACTION");
    var billHtml = "";
    var imagePath = "";
    try {
        //跳转到每张卡Iframe账单页面并获取页面
        var html = goToSrcUrl(Integer.parseInt(spanIndex));
        //如果返回html中包含“fail”,则抛异常“登录成功后页面跳转超时”
        if(html.contains("fail")){
            throw new BankException(BankConstants.BALO_99601_50, "naviget访问下载页面超时");
        }
        //跳转后等待页面渲染
        Thread.sleep(3000);
        //截取当前页面保存为图片
        imagePath = getScreenShots();
        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 跳转到第" + cardNum + "张储蓄卡账单明细下载页之后的页面截图路径" + imagePath);
        storeDataToFile(context, imagePath, "ToDownloadHtmlPath.txt")

        //获取明细起止时间
        var map = getStartAndEndDate();
        //把起止时间设为查询条件
        setCCBQueryCondition(map.get("beginDate"), map.get("endDate"),spanIndex);
        imagePath = getScreenShots();
        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 第" + cardNum + "张储蓄卡账单明细下载页设置起始时间查询之后的页面截图路径" + imagePath);
        storeDataToFile(context, imagePath, "SetQueryConditionHtmlPath.txt")
        //判断有没有账单明细，如果没有则无法下载
        var flag = isDownload(spanIndex);
        //若flag为“fail”，则无账单明细
        if (flag.equals("fail")) {
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 第" + cardNum + "张储蓄卡无账单明细!!!");
            return "无账单明细";
        }

        var params = new LinkedHashMap();
        //根据起止日期从当前frame中获取下载请求的参数
        var json = getPostParams(map.get("beginDate"), map.get("endDate"),spanIndex);
        //如果返回fail 则获取下载账单请求所需参数失败，抛异常消费明细获取失败
        if (json.contains("fail")) {
            logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 第" + cardNum + "张储蓄卡账单明细下载失败!!!");
            throw new BankException(BankConstants.BACR_20306_30, "下载历史账单明细失败!");
        }
        //获取到参数的json
        var jsonObject = JSON.parseObject(json);
        var entries = jsonObject.entrySet();
        //遍历参数，并赋值到params中
        for each (var entry in entries) {
            if (entry.getKey().equals("A_STR")) {
                var s = entry.getValue().toString().replaceAll(" ", "+");
                s += "+";
                params.put("A_STR", s);
            }
            params.put(entry.getKey(), entry.getValue().toString());
        }
        params.put("ACCSIGN", "\n" + "\n" + "\n" + "0101010|0101|人民币|0|0");
        params.put("START_DATE", map.get("beginDate"));
        params.put("END_DATE", map.get("endDate"));
        params.put("ACC_NO", cardNo);
        params.put("shangxian", "");
        params.put("xiaxian", "");
        params.put("select", "");
        params.put("TXCODE", "310206");
        params.put("clientFileName", "交易明细_" + cardFourNo + "_" + map.get("beginDate") + "_" + map.get("endDate") + ".txt");
        params.put("STR_USERID", params.get("USERID"));
        params.put("index", spanIndex.toString());
        var billUrl = "https://ibsbjstar.ccb.com.cn" + individualUrl;
        //发送请求获取消费明细
        billHtml = ajax_post_dif_ie(billUrl, params);
        storeDataToFile(context, billHtml, "bill_" + cardNum + ".txt")
    } catch ( e) {
        // statCaughtException(context, e);
        logger.info("CCBBank:taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 下载第" + cardNum + "张借记卡的账单明细失败!!!");
        throw new BankException(BankConstants.BACR_20306_30, "下载历史账单明细失败!");
    }
    return billHtml;
}


function checkFrameStatus() {
    var loginStr = getLoginParams(context)[0];
    //获取登录页面
    logger.info("CCB taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 开始登录");
    //通过js方法获取登录框所在frame的id ，为防止网站修改id造成获取不到frame的影响
    var frameId = getFrameId();
    //等待页面渲染完全，最多等待10s
    var contentWillBeCheckedFunc = function () {
        Thread.sleep(1000);
        return frame_is_exist_by_id("USERID", frameId);
    }
    var isCorrectFunc = function (contentWillBeChecked) {
        return contentWillBeChecked
    }
    context.put("frameId",frameId);
    var time = new Date().getTime();
    var data1 = new HashMap();
    data1.put("COPY_USERID", loginStr);
    data1.put("QR_CODE_ID", "undefined");
    //发送post请求，校验用户名信息是否正确
    var html1 = ajax_post("https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00?SERVLET_NAME=B2CMainPlat_00&CCB_IBSVersion=V6&PT_STYLE=1&PT_LANGUAGE=CN&TXCODE=N20008&SKEY=&time=" + time, data1);
    //如果返回页面含有如下代码，为用户名不存在，请核对用户名，此处作为参考，在后面有处理
    if (html1.contains("YDCA04310001")) {
        logger.info("ccb 建设银行 taskkey:{} , 请核对用户名", context.get(Constants.LUA_TASK_KEY));
    }
    //如果repeater状态为false，则认为页面加载不完整，保存页面并抛登录超时异常
    return  repeater(contentWillBeCheckedFunc,isCorrectFunc,10);
}

/**
 * 返回日期
 *
 * @param dateStr formatDate('20170507')
 * @return 2017-05-07
 */
function formatDate(dateStr) {
    logger.info("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + dateStr);

    if (dateStr == null || dateStr.trim().equals("")) {
        return null;
    }
    var d="";
    dateStr = RegexUtils.GetList(dateStr, "(\\d+)");
    for each ( var str in dateStr){
        d = d+str;
    }
    if(d==""){
        return null
    }

    try {
        d = DateUtils.parseDate(d, "yyyyMMdd");
    } catch (e) {
        // statCaughtException(context, e);
        logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + "解析日期格式出错" + dateStr, e);
    }
    return d;
}

/**
 * 返回月份
 *
 * @param dateStr formatDate('20170507')
 * @return 2017-05
 */
function formatMonth(dateStr) {
    if (dateStr == null || dateStr.trim().equals("")) {
        return "";
    }
    dateStr = RegexUtils.GetText(dateStr, "(\\d+)");
    var d = null;
    try {
        if(dateStr.length()==6){
            d = DateUtils.parseDate(dateStr, "yyyyMM");
        }else{
            d = DateUtils.parseDate(dateStr, "yyyyMMdd");
        }
    } catch (e) {
        // statCaughtException(context, e);
        logger.error("ccb taskKey=" + context.get(Constants.LUA_TASK_KEY) + "解析日期格式出错" + dateStr, e);
    }
    dateStr = DateFormatUtils.format(d, "yyyy-MM");
    return dateStr;
}

/**
 * 返回数字
 * 若字符串未空直接返回0
 *
 * @param numberStr
 * @return
 */
function formatNumber(numberStr) {
    if (StringUtils.isBlank(numberStr)) {
        return "0";
    }
    numberStr = RegexUtils.GetText(numberStr, "(-*\\d+\\.*\\d*)");
    return numberStr;
}


function getCreditCardAllData(){
    var creditCardAllData = new CreditCardAllData();
    creditCardAllData.setBalance(null);
    creditCardAllData.setCashBalance(null);
    creditCardAllData.setCashLimit(null);
    creditCardAllData.setCreditLimit(null);
    return creditCardAllData;
}

function getCreditCardTimeDeposit(){
    var creditCardTimeDeposit = new CreditCardTimeDeposit();
    creditCardTimeDeposit.setBalance(null);
    creditCardTimeDeposit.setInterest(null);
    creditCardTimeDeposit.setPeriod(null);
    return creditCardTimeDeposit;

}

function getBillAllData(){
    var billAllData = new BillAllData();
    billAllData.setCashLimit(null);
    billAllData.setCreditLimit(null);
    billAllData.setInterest(null);
    billAllData.setLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setMinPayment(null);
    billAllData.setNewBalance(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);
    return billAllData;
}

function getExpense(){
    var expense = new Expense();
    expense.setAmountMoney(null);
    expense.setBalance(null);
    return expense;
}

function getInstallment(){
    var installment = new Installment();
    installment.setAmountMoney(null);
    installment.setHandingFee(null);
    installment.setTransferFee(null);
    return installment;
}

function getFrameFlag(loginedHtml) {
    var frameFlag = "";
    if(loginedHtml.contains("mainfrm1")){
        frameFlag = "mainfrm1";
    }else{
        frameFlag = "mainfrm";
    }
    return frameFlag;
}

/**
 * 获取登录错误信息
 * @param loginedHtml
 */
function getLoginErrorMsg(loginedHtml,smsHtml) {
    //var loginedHtml = loginResult.get("html")
    var errorMsg = Jsoup.parse(loginedHtml).select("#error_main > div.failed_span > div > div > div:nth-child(2) > table > tbody > tr > td:nth-child(1)");
    if (errorMsg != null && errorMsg.size() > 0) {
        errorMsg = errorMsg.get(0).text();
    }


    //如果页面包含以下信息，则为尚未尚未注册或无此用户
    if (loginedHtml.contains("您输入的信息有误，请尝试用以下方式解决：") || loginedHtml.contains("未查询到相应客户信息") || loginedHtml.contains("YDCAP101NM03")) {
        return "未查询到相应客户信息";
    }

    else if(loginedHtml.contains("您的登录信息不正常") ){
        return "您的登录信息不正常";
    }
    else if(loginedHtml.contains("0130Z1108206")|| loginedHtml.contains("未能处理您的请求")){
        return "未能处理您的请求";
    }
    //如果页面包含以下信息，则为用户名密码错误
    else if (errorMsg.contains("YPWAP101NM07")) {
        return "您输入的登录密码不正确。";
    }

    //如果页面包含以下信息，则为用户名密码错误次数超限
    else if (loginedHtml.contains("YPWAP101NM08") || loginedHtml.contains("0130Z1101003")) {
        return "您输入的密码错误次数已超限。请在次日重试或重置。";
    }

    else if(errorMsg.contains("您已暂停使用网银服务功能") || loginedHtml.contains("您已暂停使用网银服务功能")){
        return "您已暂停使用网银服务功能"
    }

    //页面显示：无法找到该网页
    else if (loginedHtml.contains("无法找到该网页")) {
        return "登录超时";
    }
    //如果页面包含以下信息，则视为登录超时
    else if (loginedHtml.contains("请您在浏览器中清理并设置接受服务器下传的Cookie") || loginedHtml.contains("0130Z1108006")) {
        return "尚未注册或无此用户";
    }
    //如果页面包含以下信息，则视为会话超时
    // 0130Z1108007-->暂时未能处理您的请求
    // 0130Z1108214-->未能处理您的请求
    else if (loginedHtml.contains("暂时未能处理您的请求")|| loginedHtml.contains("0130Z1108007")||loginedHtml.contains("0130Z1108214")) {
        return "暂时未能处理您的请求,请重新登录";
    }
    //对不起，您的交易过于频繁，请稍侯再做
    else if(loginedHtml.contains("对不起，您的交易过于频繁，请稍侯再做")){
        return "对不起，您的交易过于频繁，请稍侯再做"
    }
    //如果页面包含以下信息，则为"您登录密码已超过六个月未修改，为了您网银的安全使用，请修改登录密码"
    else if (loginedHtml.contains("建议您将密码设置为")) {
        return "您登录密码已超过六个月未修改，为了您网银的安全使用，请修改登录密码";
    }
    //如果页面包含以下信息，则视为"未设置网上银行登录密码，请到官网设置"
    else if (loginedHtml.contains("您尚未设置网上银行登录密码")) {
        return "您尚未设置网上银行登录密码";
    }
    //如果页面包含以下信息，则视为登录方式错误
    else if (loginedHtml.contains("该客户只能以用户名登录")) {
        return "该客户只能以用户名登录";
    }
    //如果页面包含以下信息，则视为"您的个人网银已通过手机短信申请冻结"
    else if (loginedHtml.contains("您的个人网银已通过手机短信申请冻结")) {
        return "您的个人网银已通过手机短信申请冻结";
    }
    //如果页面包含以下信息，则视为"没有查询到您的用户信息，请先尝试官网登陆或与客服联系"
    else if (loginedHtml.contains("0130Z1108009") || loginedHtml.contains("没有查询到您的用户信息")) {
        return "尚未注册或无此用户";
    }
    //如果页面包含以下信息，则视为登录方式错误
    else if (loginedHtml.contains("您是高端版网银客户，请从高端版专用入口登录")) {
        return "您是高端版网银客户，请从高端版专用入口登录";
    } else if (loginedHtml.contains("中国建设银行网上银行个人登录验证")) {
        return "中国建设银行网上银行个人登录验证";
    }
    //如果页面包含以下信息，则视为卡片未激活，请到官网激活
    else if (loginedHtml.contains(">客户激活<")) {
        return "卡片未激活";
    }
    //如果页面包含以下信息，则视为系统繁忙
    else if (loginedHtml.contains("Hypertext Transfer Protocol")) {
        return "Hypertext Transfer Protocol";
    }
    //如果页面包含以下信息，则视为系统繁忙
    else if (loginedHtml.contains("请设置网上银行交易密码")) {
        return "请设置网上银行交易密码";
    }
    else if (loginedHtml.contains("您输入的信息含特殊字符，请重新输入")) {
        return "您输入的信息含特殊字符，请重新输入。";
    }

    else if (smsHtml.contains("暂时未能处理您的请求，请重新登录") && loginedHtml.contains("请尽量使用专用电脑操作网上银行，并定期更新操作系统安全补丁和杀毒软件") || loginedHtml.contains("您已较长时间未进行操作，为保护您的资金安全，系统已自动退出")){
        return "登录超时";
    }

    else if (loginedHtml.contains("您已暂停网银服务！如您要恢复网银服务，请正确输入账户信息和回答您的私密问题")) {
        return "您已暂停使用网银服务功能";
    }


    return "";
}